import json

from django.shortcuts import render
# 导入
from ihome.libs.captcha.captcha import captcha
from django.views import View
from django.http import HttpResponse, JsonResponse
from django_redis import get_redis_connection


class ImageCodeView(View):
    '''返回图形验证码的类视图'''

    def get(self, request):
        # 获取参数 查询字符串传参
        cur = request.GET.get('cur')

        # 调用对象的函数, 生成图片 image 和 对应的内容 text
        text, image = captcha.generate_captcha()
        redis_conn = get_redis_connection('verify_code')
        redis_conn.setex('img_%s' % cur, 120, text)
        return HttpResponse(image,
                            content_type='image/jpg')


class SmsCode(View):
    ''' 短信验证码生成'''

    def post(self, request):
        # 取出json数据 mobile id text
        dict = json.loads(request.body.decode())
        mobile = dict.get('mobile')
        id = dict.get('id')
        text = dict.get('text')

        # 判断参数完整
        if not all([mobile, id, text]):
            return JsonResponse({'errno': 4004,
                                 'errmsg': '参数不完整'})

        # 链接redis 取出图片验证码 是否过期
        redis_conn = get_redis_connection('verify_code')
        redis_conn.get('img_%s' %id)
